package com.sunchis.demo;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sunchis.demo.model.User;
import com.sunchis.demo.service.user.UserService;
import com.sunchis.demo.util.ConfigFactory;
import com.sunchis.demo.util.jgroup.JGroupAgent;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	@Resource
	private UserService userService;
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
//		User user = userService.findById("getUserById", 1);
//		System.out.println(user.getName());
//		
//		User tmpUser = new User();
//		tmpUser.setDeptId(1);
//		tmpUser.setName("许亮");
//		List<User> userList = userService.getList("getUserList", tmpUser);
//		System.out.println(userList.size());
//		
//		javax.persistence.Table table = User.class.getAnnotation(javax.persistence.Table.class);
//		System.out.println(table.name());
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@RequestMapping(value = "/jgroups", method = RequestMethod.POST)
	public String jgroups(String message, Model model){
		JGroupAgent agent = ConfigFactory.getInstance().getjGroupAgent();
		try {
			agent.sendMessage(message);
			model.addAttribute("result", message);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("result", "组播消息失败");
		}
		
		return "jgroups";
	}
}
